Overview:
- In Python, the yield statement of the form yield from <expression> enables generator functions to delegate a portion of code with yield <expression> to a subgenerator in a seamless way, forming a chain of generators and subgenerators.
- The absence of "yield from" in Python will make it difficult working with a chain of generators (if only the form yield <expression> is used), as each generator object in the chain needs to be iterated explicitly.
- Without "yield from", communicating with the inner generators using send() and throw() becomes more complex.
Example 1:
# Define class Book # Define class Chapter # Create chapters of the book chapter2Sections = ["Chapter2Section1", "Chapter2Section2"] chapter3Sections = ["Chapter3Section1", "Chapter3Section2"] chapter4Sections = ["Chapter4Section1", "Chapter4Section2"] # Create a book # Generator function that delegates to a subgenerator # Subgenerator function # Create a generator object # Navigate the generator |
Output:
Title of the Book Chapter1 Chapter1Section1 Chapter1Section2 Chapter2 Chapter2Section1 Chapter2Section2 Chapter3 Chapter3Section1 Chapter3Section2 Chapter4 Chapter4Section1 Chapter4Section2 |
Example 2:
The Python example traverses a linked list which is a recursive data structure, using yield from and prints the contents of the linked list.
# Example Python program that creates a linked list # Define the node of the linked list # Define the linked list # Function to insert a node at the end of the if self.head == None and self.tail == None: # Generator function delegating to the same subgenerator # Create a LinkedList instance # Insert values to the list # Create a generator object to print the # Print using the generator iterator |
Output:
Contents of the linked list: 1 3 4 |